package com.liuqianfei.markme.rules.inline;

import com.liuqianfei.markme.core.Token;
import com.liuqianfei.markme.rules.AbstractState;
import com.liuqianfei.markme.rules.Delimiter;
import com.liuqianfei.markme.rules.EmphasisLikeScanResult;
import com.liuqianfei.markme.rules.IAction;

/**
 * ~~strike through~~
 * @author liuqianfei
 */
public class StrikeThroughTokenizeAction implements IAction
{
    // Insert each marker as a separate text token, and add it to delimiter list
    //
    @Override
    public boolean parse(AbstractState state, boolean silent, int startLine, int endLine)
    {
        EmphasisLikeScanResult scanned;
        Token token;
        int len;
        String ch;
        int start = state.getPos();
        char marker = state.getSrc().charAt(start);

        if (silent) { return false; }

        if (marker != 0x7E/* ~ */)
            return false;

        scanned = state.scanDelims(state.getPos(), true);
        len = scanned.length;
        ch = String.valueOf(marker);

        if (len < 2)
            return false;

        if (len % 2 != 0)
        {
            token         = state.push("text", "", 0);
            token.content = ch;
            len--;
        }

        for (int i = 0; i < len; i += 2)
        {
            token         = state.push("text", "", 0);
            token.content = ch + ch;

            Delimiter delimiter = new Delimiter();
            delimiter.marker = marker;
            delimiter.jump = i;
            delimiter.token = state.getTokens().size() - 1;
            delimiter.level = state.getLevel();
            delimiter.end = -1;
            delimiter.open = scanned.can_open;
            delimiter.close = scanned.can_close;
            state.getDelimiters().add(delimiter);
        }

        state.setPos(state.getPos() + scanned.length);

        return true;
    }
}
